package com.fc.mall.portal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fc.mall.base.object.Result;
import com.fc.mall.exception.ServiceException;
import com.fc.mall.mapper.*;
import com.fc.mall.model.*;
import com.fc.mall.mapper.*;
import com.fc.mall.portal.connector.WeChatConnector;
import com.fc.mall.portal.dao.PortalMemberDao;
import com.fc.mall.portal.dao.PortalOrderDao;
import com.fc.mall.portal.domain.MemberDetails;
import com.fc.mall.portal.dto.*;
import com.fc.mall.portal.service.*;
import com.fc.mall.portal.dto.*;
import com.fc.mall.portal.util.DateUtil;
import com.fc.mall.portal.util.JwtTokenUtil;
import com.fc.mall.portal.vo.UmsMemberVO;
import com.fc.mall.util.Constants;
import com.fc.mall.vo.FanMemberVO;
import com.fc.mall.vo.MemberFansVO;
import com.fc.mall.model.*;
import com.fc.mall.portal.service.*;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * 会员管理Service实现类
 * Created by dobuy on 2018/8/3.
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisService redisService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private UmsMemberAccountService memberAccountService;
    @Autowired
    private UmsMemberUpgradeService memberUpgradeService;
    @Autowired
    private SysPropertyConfigService propertyConfigService;
    @Autowired
    private UmsMemberInviteHistoryMapper memberInviteHistoryMapper;
    @Autowired
    private OmsOrderMapper omsOrderMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    MapperFacade mapperFacade;

    @Autowired
    private PortalMemberDao portalMemberDao;
    @Autowired
    private PortalOrderDao portalOrderDao;

    @Autowired
    private UmsMemberBankMapper memberBankMapper;

    @Autowired
    private SmsCouponMapper smsCouponMapper;

    @Autowired
    private SmsCouponHistoryMapper couponHistoryMapper;

    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${authCode.expire.seconds}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private WeChatConnector weChatConnector;

    @Autowired
    private UmsIntegrationService integrationService;

    @Override
    public UmsMember getByUsername(String username) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            return memberList.get(0);
        }
        return null;
    }

    @Override
    public UmsMember getByWxOpenId(String wxOpenId) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andWxOpenIdEqualTo(wxOpenId);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            return memberList.get(0);
        }
        return null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public Result register(String username, String password, String telephone, String authCode) {
        //验证验证码
        if(!verifyAuthCode(authCode,telephone)){
            return Result.failed("验证码错误");
        }
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        example.or(example.createCriteria().andPhoneEqualTo(telephone));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers)) {
            return Result.failed("该用户已经存在");
        }
        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(username);
        umsMember.setPhone(telephone);
        umsMember.setPassword(passwordEncoder.encode(password));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        umsMember.setPassword(null);
        return Result.success("注册成功",null);
    }

    @Override
    public Result generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i=0;i<6;i++){
            sb.append(random.nextInt(10));
        }
        //验证码绑定手机号并存储到redis
        redisService.set(REDIS_KEY_PREFIX_AUTH_CODE+telephone,sb.toString());
        redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE+telephone,AUTH_CODE_EXPIRE_SECONDS);
        return Result.success("获取验证码成功",sb.toString());
    }

    @Override
    public Result updatePassword(String telephone, String password, String authCode) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(memberList)){
            return Result.failed("该账号不存在");
        }
        //验证验证码
        if(!verifyAuthCode(authCode,telephone)){
            return Result.failed("验证码错误");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(passwordEncoder.encode(password));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        return Result.success("密码修改成功",null);
    }

    @Override
    public void updateMemberInfo(WxUserInfo wxUserInfo) {
        UmsMember umsMember = getCurrentMember();
        if(umsMember != null)
        {
            try {
                if(StringUtils.isEmpty(umsMember.getNickname()) || StringUtils.isEmpty(umsMember.getIcon()))
                {
                    UmsMember updateMember = new UmsMember();
                    updateMember.setId(umsMember.getId());
                    updateMember.setNickname(URLEncoder.encode(wxUserInfo.getNickName(), "utf-8"));
                    updateMember.setWxUnionId(wxUserInfo.getUnionId());
                    updateMember.setIcon(wxUserInfo.getAvatarUrl());
                    updateMember.setCity(wxUserInfo.getCity());
                    updateMember.setGender(wxUserInfo.getGender());
                    updateMember.setPhone(wxUserInfo.getPhone());
                    memberMapper.updateByPrimaryKeySelective(updateMember);
                }
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    @Override
    public UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
        return memberDetails.getUmsMember();
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record=new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public Result wxLogin(LoginReqDto loginReqDto) {

        WxLoginRespDto wxLoginRespDto = weChatConnector.wxLogin(loginReqDto.getJsCode());
        if(wxLoginRespDto == null || wxLoginRespDto.getOpenid() == null) {
            throw new ServiceException("登陆微信服务器失败!");
        }
        String wxOpenId = wxLoginRespDto.getOpenid(); // 以微信openId做完用户名 todo

        // 通过wxOpenId 查询用户
        UmsMember member = getByWxOpenId(wxOpenId);
        if(member == null)
        {
            createNewMember(loginReqDto, wxLoginRespDto);
        }
        else
        {
            // 该微信已注册
            if(Constants.MemberLockStatus.Unlock.getValue() == member.getLockStatus().intValue()
                    && !StringUtils.isEmpty(loginReqDto.getInviteCode()))
            {
                // 如果该会员为游离状态（可变更推荐人状态），并且有邀请码时，变更该会员的推荐人
                updateMemberReferrer(member, loginReqDto.getInviteCode());
            }
        }

        String token = null;
        //密码需要客户端加密后传递
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(wxOpenId, "Future2019");
        try
        {
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            UserDetails userDetails = userDetailsService.loadUserByUsername(wxOpenId);
            token = jwtTokenUtil.generateToken(userDetails);
        }
        catch (AuthenticationException e)
        {
            e.printStackTrace();
        }

        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);

        return Result.success(tokenMap);
    }

    @Override
    public Result getMemberDetail() {
        UmsMember umsMember = getCurrentMember();
        if(umsMember != null)
        {
            UmsMemberVO umsMemberVO = mapperFacade.map(umsMember, UmsMemberVO.class);
            UmsMemberLevel umsMemberLevel = memberLevelMapper.selectByPrimaryKey(umsMember.getMemberLevelId());
            umsMemberVO.setMemberLevel(umsMemberLevel);
            return Result.success(umsMemberVO);
        }
        return null;
    }

    @Override
    public MemberFansVO getMemberFans(Map<String, Object> params) {
        MemberFansVO memberFansVO = new MemberFansVO();
        // 获取当前用户
        UmsMember umsMember = getCurrentMember();
        if(umsMember != null) {
            // 1. 获取粉丝总数
            UmsMemberInviteHistoryExample example = new UmsMemberInviteHistoryExample();
            example.createCriteria().andMemberIdEqualTo(umsMember.getId());


            Integer count = memberInviteHistoryMapper.countByExample(example);
            memberFansVO.setFansNumber(count);

            // 2. 根据分页信息获取粉丝列表
            params.put("memberId", umsMember.getId());
            List<FanMemberVO>  fanMemberList  = new ArrayList<>();
            List<FanMemberVO>  fanMemberVOList = memberInviteHistoryMapper.queryMembersByParentMemberId(params);
            if(null != fanMemberVOList && !fanMemberVOList.isEmpty())
            {
               for(FanMemberVO fanMember: fanMemberVOList)
               {
                   if(null != fanMember.getMemberId())
                   {
                       try {
                           fanMember.setNickName(URLDecoder.decode(StringUtils.isEmpty(fanMember.getNickName()) ? "未授权用户" : fanMember.getNickName(), "utf-8"));
                           fanMember.setIcon(StringUtils.isEmpty(fanMember.getIcon()) ? Constants.DEFAULT_HEADPORTAL : fanMember.getIcon());
                           OmsOrderExample orderExample = new OmsOrderExample();
                           orderExample.createCriteria().andMemberIdEqualTo(fanMember.getMemberId()).andStatusBetween(1, 3);
                           orderExample.setOrderByClause("payment_time desc");
                           List<OmsOrder> omsOrders =  omsOrderMapper.selectByExample(orderExample);
                           if(null != omsOrders && !omsOrders.isEmpty())
                           {
                               fanMember.setLastPayTime(omsOrders.get(0).getPaymentTime());
                               fanMember.setPayOrderCount(omsOrders.size());
                               BigDecimal totalAmount = new BigDecimal(0);
                               for(OmsOrder omsOrder: omsOrders)
                               {
                                   totalAmount = totalAmount.add(omsOrder.getPayAmount());
                               }
                               fanMember.setPayAmount(totalAmount);
                               fanMember.setOrderAmount(totalAmount.divide(new BigDecimal(omsOrders.size())).setScale(2));
                           }
                           else
                           {
                               fanMember.setPayOrderCount(0);
                               fanMember.setPayAmount(new BigDecimal(0));
                               fanMember.setOrderAmount(new BigDecimal(0));
                           }

                       } catch (Exception e) {
                           e.printStackTrace();
                       }
                       fanMemberList.add(fanMember);
                   }


               }
            }
            memberFansVO.setFansMembers(fanMemberList);
        }
        return memberFansVO;
    }

    @Override
    public JSONObject getMyReferrer() {
        JSONObject respJson = new JSONObject();

        UmsMember umsMember = getCurrentMember();
        if(umsMember != null && umsMember.getParentMemberId() != null)
        {
            UmsMemberInviteHistoryExample example = new UmsMemberInviteHistoryExample();
            example.createCriteria().andMemberIdEqualTo(umsMember.getParentMemberId());
            example.createCriteria().andChildMemberIdEqualTo(umsMember.getId());
            example.createCriteria().andEffectiveEqualTo(1);
            List<UmsMemberInviteHistory> memberInviteHistoryList = memberInviteHistoryMapper.selectByExample(example);
            if(!CollectionUtils.isEmpty(memberInviteHistoryList))
            {
                UmsMemberInviteHistory memberInviteHistory = memberInviteHistoryList.get(0);
                UmsMember parentMember = memberMapper.selectByPrimaryKey(umsMember.getParentMemberId());
                if(parentMember != null)
                {
                    try {
                        parentMember.setNickname(URLDecoder.decode(parentMember.getNickname(), "utf-8"));

                    }catch (Exception e) {

                    }
                    respJson.put("parentMember", parentMember);
                    respJson.put("inviteTime", memberInviteHistory.getInviteTime());
                }
            }
        }

        return respJson;
    }

    /**
     * 会员下订单时需要调用该接口
     * 当新用户第一次购物时再规定时间内购物的话，锁死推荐人
     * @param umsMember
     */
    public void convertToEffectiveMember(UmsMember umsMember)
    {
        if(umsMember != null
                && Constants.MemberLockStatus.TempLock.getValue() == umsMember.getLockStatus()
                && umsMember.getParentMemberId() != null)
        {
            // 变为有效用户，并锁死推荐人
            //memberUpgradeService.handleInviteMember(umsMember.getParentMemberId(), umsMember.getId());

            // 更新用户的锁定状态
            UmsMember updateMember = new UmsMember();
            updateMember.setId(umsMember.getId());
            updateMember.setLockStatus(Constants.MemberLockStatus.Lock.getValue());
            updateMember.setLockTime(new Date());
            memberMapper.updateByPrimaryKeySelective(updateMember);
        }
    }

    /**
     * 更新，重置新会员的锁定推荐人状态
     */
    public void resetMemberLockStatus() {
        Integer lockReferer = propertyConfigService.getLockReferer();

        if(Constants.NeedToLock.NeedLock.getValue() == lockReferer)
        {
            // 获取在一定时间内没有购物的新会员，并更新锁定推荐人状态
            Integer tempLockHours = propertyConfigService.getLockDuration();
            Date lockDate = DateUtil.addHours(new Date(), -tempLockHours);

            UmsMemberExample example = new UmsMemberExample();
            example.createCriteria().andLockStatusEqualTo(Constants.MemberLockStatus.TempLock.getValue()).andLockTimeLessThan(lockDate);
            List<UmsMember> umsMemberList = memberMapper.selectByExample(example);

            if(!CollectionUtils.isEmpty(umsMemberList))
            {
                for(UmsMember umsMember: umsMemberList)
                {
                    umsMember.setLockStatus(Constants.MemberLockStatus.Unlock.getValue());
                    umsMember.setLockTime(null);
                    memberMapper.updateByPrimaryKey(umsMember);
                }
            }
        }
    }

    @Override
    public void recoveryExpiredCoupon() {
        SmsCouponExample couponExample = new SmsCouponExample();
        couponExample.createCriteria().andEndTimeLessThan(new Date());
        List<SmsCoupon> couponList = smsCouponMapper.selectByExample(couponExample);
        List<Long> couponIds = new ArrayList<>();
        if(null != couponList && !couponList.isEmpty())
        {
            for (SmsCoupon coupon : couponList)
            {
                couponIds.add(coupon.getId());
            }
        }

        if(!couponIds.isEmpty())
        {
            SmsCouponHistoryExample historyExample = new SmsCouponHistoryExample();
            historyExample.createCriteria().andUseStatusEqualTo(0).andCouponIdIn(couponIds);

            SmsCouponHistory couponHistory = new SmsCouponHistory();
            couponHistory.setUseStatus(2);
            couponHistoryMapper.updateByExampleSelective(couponHistory, historyExample);
        }
    }

    @Override
    public byte[] generateQrCode(String page, Map<String, Object> params) {
        String accessToken = weChatConnector.getAccessToken();
        UmsMember currentMember = getCurrentMember();
        StringBuilder queryBuilder = new StringBuilder();
        queryBuilder.append(currentMember.getId().toString());
        if(!params.isEmpty())
        {
            params.keySet().forEach(key -> {
                queryBuilder.append(",").append(params.get(key));
            });
        }
        byte[] qrCode = weChatConnector.generateQrCode(accessToken, queryBuilder.toString(), page);
        return qrCode;
    }

    @Override
    public AgentBasicInfo getAgentBasicInfo() {
        UmsMember curMember = getCurrentMember();
        UmsMemberAccount memberAccount = memberAccountService.getMemberAccountInfo();
        Long fansCount = portalMemberDao.getFansCount(curMember.getId());
        Long fansOrderCount = portalOrderDao.getFansOrderCount(curMember.getId());
        BigDecimal totalEarnings = new BigDecimal(memberAccount.getTotalAmount()).divide(new BigDecimal(100));
        AgentBasicInfo agentBasicInfo = new AgentBasicInfo(totalEarnings, fansOrderCount.intValue(), fansCount.intValue());
        return agentBasicInfo;
    }

    @Override
    public int updateMemberWxAppPhone(DecodePhoneParam decodePhoneParam) {
        try {
            String phone = weChatConnector.decodeWxAPPPhone(decodePhoneParam);
            UmsMember currentMember = getCurrentMember();
            if(StringUtils.isEmpty(currentMember.getPhone()) && !StringUtils.isEmpty(phone))
            {
                UmsMember newMember = new UmsMember();
                newMember.setId(currentMember.getId());
                newMember.setPhone(phone);
                return memberMapper.updateByPrimaryKeySelective(newMember);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 创建新会员及账户等信息
     * @param loginReqDto
     * @param wxLoginRespDto
     */
    private void createNewMember(LoginReqDto loginReqDto, WxLoginRespDto wxLoginRespDto)
    {
        // 该用户第一次登陆小程序，则需要创建一个新用户
        // 新用户登陆
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(wxLoginRespDto.getOpenid());
        umsMember.setWxOpenId(wxLoginRespDto.getOpenid());
        umsMember.setWxUnionId(wxLoginRespDto.getUnionid());
        umsMember.setPassword(passwordEncoder.encode("Future2019"));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        //初始化会员等级类型为 普通会员
        umsMember.setLevelType(Constants.MemberLevelType.Member.getValue());
        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList))
        {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }

        UmsMember parentMember = getMemberByInviteCode(loginReqDto.getInviteCode());
        if(parentMember != null)
        {
            String parentPath = (StringUtils.isEmpty(parentMember.getParentPath())  ? "" : parentMember.getParentPath()) + ',' + parentMember.getId();
            umsMember.setParentMemberId(parentMember.getId());
            umsMember.setParentPath(parentPath);

            //邀请获取积分
            integrationService.getIntegration(parentMember.getId(), Constants.SourceTypeEnum.INVITE);

        }

        // 设定是否会员的锁定状态
        Integer lockReferer = propertyConfigService.getLockReferer();
        if(Constants.NeedToLock.NeedLock.getValue() == lockReferer.intValue())
        {
            // 临时锁定会员的推荐人，等待新会员购物锁死推荐人
            umsMember.setLockStatus(Constants.MemberLockStatus.TempLock.getValue());
        }
        else
        {
            // 直接锁定会员的推荐人
            umsMember.setLockStatus(Constants.MemberLockStatus.Lock.getValue());
        }
        umsMember.setLockTime(new Date());

        memberMapper.insert(umsMember);

        // 初始化会员账户， 升级状态等信息
        initMemberExtraInfo(umsMember);

        // 如果推荐新人设置中，无临时锁定期，直接锁定则锁定该用户的推荐人
        memberUpgradeService.handleInviteMember(umsMember.getParentMemberId(), umsMember.getId());

    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone){
        if(StringUtils.isEmpty(authCode)){
            return false;
        }
        String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
        return authCode.equals(realAuthCode);
    }

    /**
     * 初始化会员的额外信息，例如账户，升级状态等
     * @param umsMember
     */
    private void initMemberExtraInfo(UmsMember umsMember)
    {
        // 初始化用户账户信息
        memberAccountService.initMemberAccount(umsMember);
        // 初始化用户升级条件
        memberUpgradeService.initMemberUpgrade(umsMember);
    }

    /**
     * 通过邀请码获取用户信息
     * @param inviteCode
     * @return
     */
    private UmsMember getMemberByInviteCode(String inviteCode)
    {
        if(!StringUtils.isEmpty(inviteCode))
        {
            try
            {
                Long parentId = Long.valueOf(inviteCode);
                return getById(parentId); // todo inviteCode
            }
            catch (Exception e)
            {
                return null;
            }

        }
        return null;
    }

    /**
     * 变更会员的推荐人
     * @param member
     * @param inviteCode
     */
    private void updateMemberReferrer(UmsMember member, String inviteCode)
    {
        if(StringUtils.isEmpty(inviteCode))
        {
            return;
        }

        UmsMember parentMember = getMemberByInviteCode(inviteCode);
        if(parentMember != null && !parentMember.getId().equals(member.getParentMemberId())
                && !parentMember.getId().equals(member.getId()))
        {
            Long memberOldParentId = member.getParentMemberId();
            // 1. 更新用户的推荐人及parentPath
            member.setParentMemberId(parentMember.getId());
            String parentPath = (parentMember.getParentPath() == null ? "" : parentMember.getParentPath()) + ',' + parentMember.getId();
            member.setParentPath(parentPath);
            // 临时锁定推荐人，等待新会员购物锁死推荐人
            member.setLockStatus(Constants.MemberLockStatus.TempLock.getValue());
            member.setLockTime(new Date());
            memberMapper.updateByPrimaryKey(member);

            // 2. 更新该会员的下级会员的parentPath
            UmsMemberExample example = new UmsMemberExample();
            example.createCriteria().andParentPathLike("," + member.getId());
            List<UmsMember> childMemberList = memberMapper.selectByExample(example);
            if(!CollectionUtils.isEmpty(childMemberList))
            {
                for (UmsMember childMember: childMemberList)
                {
                    if(!StringUtils.isEmpty(childMember.getParentPath()))
                    {
                        String newParentPath = childMember.getParentPath().replace("," + memberOldParentId, "," + member.getParentMemberId());
                        childMember.setParentPath(newParentPath);
                        memberMapper.updateByPrimaryKey(childMember);
                    }
                }
            }

            //更新粉丝推荐
            UmsMemberInviteHistoryExample umsMemberInviteHistoryExample = new UmsMemberInviteHistoryExample();
            umsMemberInviteHistoryExample.createCriteria().andChildMemberIdEqualTo(member.getId());
            List <UmsMemberInviteHistory> inviteHistorys = memberInviteHistoryMapper.selectByExample(umsMemberInviteHistoryExample);
            UmsMemberInviteHistory inviteHistory;
            if (null == inviteHistorys || inviteHistorys.isEmpty())
            {
                memberUpgradeService.handleInviteMember(parentMember.getId(), member.getId());
                return;
            }
            inviteHistory = inviteHistorys.get(0);
            inviteHistory.setMemberId(parentMember.getId());
            memberInviteHistoryMapper.updateByPrimaryKeySelective(inviteHistory);
        }
    }
}
